package com.eqdd.yiqidian.ui.companyspace

import android.app.AlertDialog
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.ui.mine.space.OwnerComSpaceActivity
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_space.view.*
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast
import java.util.*

/**
 * Created by jhj on 18-7-30.
 */
class CollectionFragment : Fragment() {

    var pageNum = 0

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_space, container, false)
        setView(view)
        return view
    }

    private fun setView(view: View) {
        val userGuid = arguments?.getString(Config.ID)
        val companyId = arguments?.getInt(Config.COMPANY_ID) ?: 0
        val status = arguments?.getInt(Config.STATUS) ?: -1
        view.recyclerView.layoutManager = LinearLayoutManager(activity)
        view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
        val mvcHelper = MVCCoolHelper<List<ItemBean>>(view.coolRefreshView)
        val list = arrayListOf<ItemBean>()
        val slimAdapterEx = SlimAdapterEx.create().register<ItemBean>(R.layout.list_item_173, SlimInjector<ItemBean> { data, injector ->

            if (status == 1) {
                injector?.image(R.id.imageView, data?.productImage)
                        ?.text(R.id.tv_content, data?.productName)
                        ?.text(R.id.tv_price, "￥" + data?.productPrice + "元")
                        ?.gone(R.id.tv_company)
                        ?.visible(R.id.recyclerView)
            } else {
                injector?.image(R.id.imageView, data?.comLogo)
                        ?.text(R.id.tv_company, data?.company)
                        ?.gone(R.id.recyclerView)
                        ?.visible(R.id.tv_company)
            }

        }).attachTo(view.recyclerView).updateData(list as List<ItemBean>?) as SlimAdapterEx<ItemBean>?

        ItemClickSupport.addTo(view.recyclerView)
                .setOnItemLongClickListener { recyclerView, position, v ->

                    val data = slimAdapterEx?.data?.get(position)
                    AlertDialog.Builder(activity)
                            .setTitle("提示")
                            .setMessage("是否取消收藏${"“${if (status == 1) data?.productName else data?.company
                                    ?: ""}”?"}")
                            .setPositiveButton("取消", null)
                            .setNegativeButton("确定", { _, _ ->
                                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.COLLECT_CANCEL)
                                        .params("userGuid", userGuid)
                                        .params("companyId", companyId)
                                        .params("collectId", slimAdapterEx?.getDataItem(position)?.Id
                                                ?: 0)
                                        .execute(object : DialogCallBack<HttpResult<*>>(activity) {
                                            override fun onSuccess(response: Response<HttpResult<*>>?) {
                                                val result = response?.body()
                                                if (result?.status == 200) {
                                                    toast(result.msg ?: "取消收藏成功")
                                                    mvcHelper.refresh()
                                                } else {
                                                    toast(result?.msg ?: "")
                                                }
                                            }
                                        })
                            })
                            .show()
                    true
                }.setOnItemClickListener { recyclerView, position, v ->
                    val data = slimAdapterEx?.data?.get(position)
                    if (status == 1) {
                        startActivity<ProductInfoActivity>(Config.ID to (data?.productId
                                ?: 0))
                    } else {
                        startActivity<OwnerComSpaceActivity>(Config.COMPANY_ID to companyId)
                    }
                }


        val url = if (status == 1) {
            HttpConfig.BASE_URL + HttpConfig.COLLECT_PRODUCT_GET
        } else {
            HttpConfig.BASE_URL + HttpConfig.COLLECT_COMPANY_GET
        }

        val dataSource = ModelRx2DataSource<ItemBean>(ModelRx2DataSource.OnLoadSource<ItemBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<ItemBean>>>(url)
                    .params("companyId", companyId)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<ItemBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<ItemBean>>>())
                    .flatMap({ result ->
                        pageNum = result.page
                        if (page == 1) {
                            mvcHelper.isAutoLoadMore = true
                        }
                        val dataList = if (result.items == null)
                            ArrayList()
                        else
                            result.items as MutableList<ItemBean>?
                        Flowable.just<MutableList<ItemBean>>(dataList)
                    })
        }, 10)


        mvcHelper.setDataSource(dataSource)
        mvcHelper.adapter = slimAdapterEx
        mvcHelper.refresh()
    }

    class ItemBean {
        val Id: Int = 0
        val company: String = ""
        val comLogo: String = ""
        val companyId = 0
        val productName: String = ""
        val productImage: String = ""
        val productPrice: Double = 0.0
        val productId: Int = 0
    }

}